package com.base.controller.coupon_api;

import com.base.po.coupon.QueryStockResponse;
import com.base.po.coupon_prestore.CouponBrandPrestore;
import com.base.po.coupon_prestore.CouponCategoryPrestore;
import com.base.po.coupon_prestore.CouponGoodsPrestore;
import com.base.po.coupon_prestore.CouponOrderPrestore;
import com.base.po.coupon_sdk.CouponInfoUtil;
import com.base.po.param.NetState;
import com.base.po.voip_coupon.CouponPayOrder;
import com.base.po.voip_coupon.return_po.*;
import com.base.service.COUPON.*;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import com.base.utils.Base64Util;
import com.base.utils.Page;
import com.base.utils.Produce;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 365优惠券
 *
 * @author K
 */
@RestController
@RequestMapping("/couponPrestore")
public class CouponPrestoreController {
    private final UsersService usersService;
    private final SubscribersService subscribersService;
    private final CouponCategoryPrestoreService couponCategoryPrestoreService;
    private final CouponBrandPrestoreService couponBrandPrestoreService;
    private final CouponGoodsPrestoreService couponGoodsPrestoreService;
    private final CouponOrderPrestoreService couponOrderPrestoreService;
    private final CouponPayOrderService couponPayOrderService;

    @Autowired
    public CouponPrestoreController(UsersService usersService, SubscribersService subscribersService, CouponCategoryPrestoreService couponCategoryPrestoreService, CouponBrandPrestoreService couponBrandPrestoreService, CouponGoodsPrestoreService couponGoodsPrestoreService, CouponOrderPrestoreService couponOrderPrestoreService, CouponPayOrderService couponPayOrderService) {
        this.usersService = usersService;
        this.subscribersService = subscribersService;
        this.couponCategoryPrestoreService = couponCategoryPrestoreService;
        this.couponBrandPrestoreService = couponBrandPrestoreService;
        this.couponGoodsPrestoreService = couponGoodsPrestoreService;
        this.couponOrderPrestoreService = couponOrderPrestoreService;
        this.couponPayOrderService = couponPayOrderService;
    }

    // 365优惠券首页
    @RequestMapping(value = "/index", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState index(HttpServletRequest request, String parentId, String userId) throws Exception {
        NetState netState = new NetState();

        if (parentId == null || parentId.isEmpty()) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("数据异常");
            return netState;
        }

        parentId = null;
        // 查询所有分类
        List<CouponCategoryPrestore> categories = couponCategoryPrestoreService.selectAll(null, parentId, 2);

        // 返回所有分类
        List<CategoryPo> categoryPos = new ArrayList<>();
        // 返回所有品牌
        List<BrandPo> brandPos = null;
        List<BrandsPo> brandsPos = new ArrayList<>();
        // 返回推荐品牌
        List<BrandPo> recommendBrandPos = new ArrayList<>();
        for (CouponCategoryPrestore category : categories){
            // 分类
            CategoryPo categoryPo = new CategoryPo();
            categoryPo.setId(category.getId());
            categoryPo.setCategoryName(category.getCategory());
            categoryPos.add(categoryPo);

            // 品牌
            brandPos = new ArrayList<>();
            BrandsPo brandsPo = new BrandsPo();
            brandsPo.setCategoryId(category.getId());
            brandsPo.setCategoryName(category.getCategory());
            List<CouponBrandPrestore> brands = couponBrandPrestoreService.selectAll(null, parentId, category.getId(), null, 2);
            for (CouponBrandPrestore brand : brands){
                BrandPo brandPo = new BrandPo();
                brandPo.setId(brand.getId());
                brandPo.setBrandName(brand.getCategory());
                brandPo.setBrandPic(brand.getPic());
                brandPos.add(brandPo);
                if (brand.getLevel() != null && brand.getLevel() == 1){
                    recommendBrandPos.add(brandPo);
                }
            }
            brandsPo.setBrandPos(brandPos.isEmpty() ? null : brandPos);
            brandsPos.add(brandsPo);
        }

        Map<String, Object> map = new HashedMap();
        map.put("categories", categoryPos);
        map.put("brands", brandsPos);
        map.put("recommendBrands", recommendBrandPos);

        netState.setErrorCode(NetState.SUCCESS_CONN);
        netState.setData("查询成功");
        netState.setJson(map);
        return netState;
    }

    // 365优惠券商品
    @RequestMapping(value = "/goods", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState goods(HttpServletRequest request, String parentId, String userId, String categoryId, String brandId) {
        NetState netState = new NetState();

        if (parentId == null || parentId.isEmpty() || brandId == null || brandId.isEmpty()) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("数据异常");
            return netState;
        }

        parentId = null;
        // 查询品牌
        List<CouponBrandPrestore> brands = couponBrandPrestoreService.selectAll(null, parentId, categoryId, null, 2);
        // 返回品牌
        List<BrandPo> brandPos = new ArrayList<>();
        for (CouponBrandPrestore brand : brands){
            BrandPo brandPo = new BrandPo();
            brandPo.setId(brand.getId());
            brandPo.setBrandName(brand.getCategory());
            brandPo.setBrandPic(brand.getPic());
            brandPos.add(brandPo);
        }

        // 查询商品
        List<CouponGoodsPrestore> goodses = couponGoodsPrestoreService.selectAllDetail(null, parentId, brandId);
        // 返回商品
        List<GoodsPo> goodsPos = new ArrayList<>();

        for (CouponGoodsPrestore goods : goodses){
            GoodsPo goodsPo = new GoodsPo();
            goodsPo.setId(goods.getId());
            goodsPo.setBrandId(goods.getBrandid());
            goodsPo.setName(goods.getName());
            goodsPo.setPic(goods.getPic());
            goodsPo.setOfficialPrices(goods.getOfficialprices());
            goodsPo.setSalePrices(goods.getSaleprices());
            goodsPo.setSaveContent(goods.getShowcontent());
            try {
                QueryStockResponse response = CouponInfoUtil.queryStock(goods.getId());
                goodsPo.setStock(response.getData().getStock_num());
            }catch (Exception e){
                goodsPo.setStock(0);
            }
            goodsPos.add(goodsPo);
        }

        Map<String, Object> map = new HashedMap();
        map.put("brands", brandPos.isEmpty() ? null : brandPos);
        map.put("goodses", goodsPos.isEmpty() ? null : goodsPos);

        netState.setErrorCode(NetState.SUCCESS_CONN);
        netState.setData("查询成功");
        netState.setJson(map);
        return netState;
    }

    // 365优惠券商品详情
    @RequestMapping(value = "/goodsDetails", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState goodsDetails(HttpServletRequest request, String goodsId) {
        NetState netState = new NetState();

        if (goodsId == null || goodsId.isEmpty()) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("数据异常");
            return netState;
        }

        CouponGoodsPrestore goods = couponGoodsPrestoreService.selectByPrimaryKey(goodsId);

        GoodsPo goodsPo = new GoodsPo();
        goodsPo.setId(goods.getId());
        goodsPo.setName(goods.getName());
        goodsPo.setPic(goods.getPic());
        goodsPo.setOfficialPrices(goods.getOfficialprices());
        goodsPo.setSalePrices(goods.getSaleprices());

        netState.setErrorCode(NetState.SUCCESS_CONN);
        netState.setData("查询成功");
        netState.setJson(goodsPo);
        return netState;
    }

    // 365优惠券订单
    @RequestMapping(value = "/orders", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState orders(HttpServletRequest request, String parentId, String userId, Integer orderStatus, Integer status, Integer pageNo){
        NetState netState = new NetState();

        if (parentId == null || parentId.isEmpty() || userId == null || userId.isEmpty()) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("数据异常");
            return netState;
        }

        if (status == 0){
            status = null;
        }

        // 查询订单
        Page page = new Page();
        page.setCurrentPageNo(pageNo);
        page.setRecordTotal(couponOrderPrestoreService.countAll(parentId, userId, orderStatus, status));
        List<CouponOrderPrestore> orders = couponOrderPrestoreService.selectAll(page, parentId, userId, orderStatus, status);
        // 返回订单
        List<OrdersPo> ordersPos = new ArrayList<>();
        for (CouponOrderPrestore order : orders){
            CouponPayOrder payOrder = couponPayOrderService.selectByPrimaryKey(order.getId());

            OrdersPo ordersPo = new OrdersPo();
            ordersPo.setId(order.getId());
            ordersPo.setProductId(order.getProductid());
            ordersPo.setProductName(payOrder.getProductname());
            ordersPo.setUnitPrice(payOrder.getUnitprice());
            ordersPo.setCreateTime(order.getCouponcreatetime());
            ordersPo.setCreateTime(order.getCouponcreatetime());
            ordersPo.setEndTime(Produce.plusDay(1, order.getCouponcreatetime()));
            ordersPo.setStatus(order.getStatus());
            ordersPo.setOrderFlag(Base64Util.encodeData(order.getId() + "/" + order.getFlag()));

            CouponGoodsPrestore goods = couponGoodsPrestoreService.selectByPrimaryKey(order.getProductid());
            ordersPo.setProductPic(goods.getPic());

            ordersPos.add(ordersPo);
        }

        netState.setErrorCode(NetState.SUCCESS_CONN);
        netState.setData("查询成功");
        netState.setJson(pageNo > page.getPageTotal() ? null : ordersPos.size() > 0 ? ordersPos : null);
        return netState;
    }

    // 365优惠券订单详情
    @RequestMapping(value = "/orderDetails", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState orderDetails(HttpServletRequest request, String orderFlag){
        NetState netState = new NetState();

        if (orderFlag == null) {
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("数据异常");
            return netState;
        }

        Integer flag = null;
        try {
            orderFlag = Base64Util.decodeData(orderFlag).split("/")[1];
            flag = Integer.valueOf(orderFlag);
        }catch (Exception e) {
            netState.setErrorCode(NetState.SYSTEM_ERROR);
            netState.setData("订单异常");
            return netState;
        }
        if (flag == null){
            netState.setErrorCode(NetState.PARAMS_ERROR);
            netState.setData("订单错误");
            return netState;
        }

        // 订单信息
        CouponOrderPrestore order = couponOrderPrestoreService.selectByFlag(flag);
        // 订单信息
        CouponPayOrder payOrder = couponPayOrderService.selectByPrimaryKey(order.getId());
        // 商品信息
        CouponGoodsPrestore goods = couponGoodsPrestoreService.selectByPrimaryKey(order.getProductid());

        OrderPo orderPo = new OrderPo();
        orderPo.setProductId(payOrder.getProductid());
        orderPo.setProductName(payOrder.getProductname());
        orderPo.setCardType(order.getCardtype());
        orderPo.setCardNo(order.getCardno());
        orderPo.setCardPwd(order.getCardpwd());
        orderPo.setLinkUrl(order.getLinkurl());
        orderPo.setUniqueCode(order.getUniquecode());
        orderPo.setUnitPrice(payOrder.getUnitprice());
        orderPo.setCreateTime(order.getCouponcreatetime());
        orderPo.setEndTime(Produce.plusDay(1, order.getCouponcreatetime()));
        orderPo.setSaveContent(goods.getShowcontent());
        orderPo.setStatus(order.getStatus());

        netState.setErrorCode(NetState.SUCCESS_CONN);
        netState.setData("查询成功");
        netState.setJson(orderPo);
        return netState;
    }
}
